package org.example;

import java.lang.reflect.Field;

/**
 * 演示@Auotwired的绑定原理. field.set()
 *
 * @Auotwired 中并未调用 setter 方法
 *
 * 可以看到 成员变量user12,绑定的过程中,并未调用任务后setter方法
 */
public class AppSpringAutowire {

    public User user12;

    public static void main(String[] args) throws Exception {

        Class<AppSpringAutowire> clazz = AppSpringAutowire.class;

        AppSpringAutowire springAutowire = clazz.newInstance();

        User user = new User("时春跃", 33);

//        Field userField = clazz.getDeclaredField("user12");

        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields
        ) {
            if (user.getClass() == field.getGenericType()) {
                System.out.println("绑定前:"+springAutowire);
                //field.set(whichObject,value) ,第一个参数是要第二个参数值设置给哪个对象，第二个参数是要设置的值
                field.set(springAutowire, user); // 核心绑定方法
                System.out.println("绑定后:"+springAutowire);
            }
        }

    }

    @Override
    public String toString() {
        return "AppSpringAutowire{" +
                "user=" + user12 +
                '}';
    }

    // 该setter方法未被调用
    public void setUser12(User user12) {
        System.out.println("setUser12执行了");
        this.user12 = user12;
    }

    // 该setter方法未被调用
    public void setUser(User user12) {
        System.out.println("setUser执行了");
        this.user12 = user12;
    }

}
